﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;

namespace ERP_SaaS_WinForm.销售
{
    public partial class AddContract : Form
    {
        /// <summary>
        /// 合同编号
        /// </summary>
        public string ContractCode { get; set; }
        /// <summary>
        /// 合同名称
        /// </summary>
        public string ContractName { get; set; }
        /// <summary>
        /// 客户Id（主键唯一标识）
        /// </summary>
        public int ClientId { get; set; }
        /// <summary>
        /// 签订日期
        /// </summary>
        public DateTime SigningDate { get; set; }
        /// <summary>
        /// 发货日期
        /// </summary>
        public DateTime ShippingDate { get; set; }
        /// <summary>
        /// 合同金额
        /// </summary>
        public double DiscountAmount { get; set; }
        /// <summary>
        /// 送货地址
        /// </summary>
        public string DeliveryAdder { get; set; }
        /// <summary>
        ///是否审核0未审核1已通过2已驳回
        /// </summary>
        public int ContractState { get; set; }
        /// <summary>
        /// 合同备注
        /// </summary>
        public string ContractRemark { get; set; }
        /// <summary>
        /// 当前登录人（审批人）
        /// </summary>
        public int LoginUserId { get; set; }
        public AddContract()
        {
            InitializeComponent();
        }

        private async void btnAddContract_Click(object sender, EventArgs e)
        {
            try
            {
                if(string.IsNullOrEmpty(txtContractCode.Text.Trim()))
                {
                    MessageBox.Show("请输入销售合同编号");
                    return;
                }
                if (string.IsNullOrEmpty(txtContractName.Text.Trim()))
                {
                    MessageBox.Show("请输入销售合同名称");
                    return;
                }
                if (string.IsNullOrEmpty(txtDiscountAmount.Text.Trim()) || !double.TryParse(txtDiscountAmount.Text.Trim(), out double amount))
                {
                    MessageBox.Show("请输入正确的销售合同金额");
                    return;
                }
                if (string.IsNullOrEmpty(txtDeliveryAdder.Text.Trim()))
                {
                    MessageBox.Show("请输入销售合同送货地址");
                    return;
                }
                // 备注可为空

                if (ClientId <= 0)
                {
                    MessageBox.Show("请先选择客户");
                    return;
                };

                var payload = new
                {
                    ContractCode = txtContractCode.Text.Trim(),
                    ContractName = txtContractName.Text.Trim(),
                    ClientId = ClientId,
                    SigningDate = dateSigningDate.Value.ToString("yyyy-MM-dd"),
                    ShippingDate = dateShippingDate.Value.ToString("yyyy-MM-dd"),
                    DiscountAmount = amount,
                    DeliveryAdder = txtDeliveryAdder.Text.Trim(),
                    ContractState = 0,
                    ContractRemark = txtContractRemark.Text.Trim(),
                    LoginUserId = 0
                };

                string apiUrl = "http://10.223.8.6:3530/api/Contract/AddContract";
                using (var http = new HttpClient())
                {
                    string json = JsonConvert.SerializeObject(payload);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var resp = await http.PostAsync(apiUrl, content);
                    string respText = await resp.Content.ReadAsStringAsync();
                    if (resp.IsSuccessStatusCode)
                    {
                        dynamic result = JsonConvert.DeserializeObject(respText);
                        if (result != null && result.code == 200)
                        {
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                            return;
                        }
                        MessageBox.Show($"添加失败: {result?.msg ?? respText}");
                    }
                    else
                    {
                        MessageBox.Show($"添加失败：{resp.StatusCode}\n{respText}");
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void btnSelectClient_Click(object sender, EventArgs e)
        {
            var clientForm = new Client();
            if (clientForm.ShowDialog(this) == DialogResult.OK && clientForm.SelectedClient != null)
            {
                ClientId = clientForm.SelectedClient.ClientId;
                txtClient.Text = clientForm.SelectedClient.ClientName;
            }
        }
    }
}
